package com.lzy.article.html.controller;

import com.lzy.api.controller.article.ArticleHTMLControllerApi;
import com.mongodb.client.gridfs.GridFSBucket;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Component
public class ArticleHTMLComponent {

    @Value("${freemarker.html.article}")
    private String articlePath;

    @Autowired
    private GridFSBucket gridFSBucket;

    public Integer download(String articleId, String articleMongoId) throws Exception {

        // 1. 拼接最终文件的保存地址
        String path = articlePath + File.separator + articleId + ".html";
        // 2. 获取文件流，定义存放位置和名称
        File file = new File(path);
        // 3. 创建输出流
        OutputStream os = new FileOutputStream(file);
        // 4. 执行下载
        gridFSBucket.downloadToStream(new ObjectId(articleMongoId), os);

        os.close();
        return HttpStatus.OK.value();
    }

    public Integer delete(String articleId) throws Exception {

        // 拼接最终文件的保存的地址
        String path = articlePath + File.separator + articleId + ".html";

        // 获取文件流，定义存放的位置和名称
        File file = new File(path);

        // 删除文件
        if(file.exists()){
            file.delete();
        }
        return HttpStatus.OK.value();
    }
}


